package cn.gson.CRM.controller.order;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import cn.gson.CRM.model.entity.ReceiveRecord;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.gson.CRM.model.dao.customers.AddressDao;
import cn.gson.CRM.model.dao.customers.CustomersDao;
import cn.gson.CRM.model.dao.fund.PayPlanDao;
import cn.gson.CRM.model.dao.fund.ReceivePlanDao;
import cn.gson.CRM.model.dao.fund.ReceiveRecordDao;
import cn.gson.CRM.model.dao.index.MessageDao;
import cn.gson.CRM.model.dao.order.OrderDao;
import cn.gson.CRM.model.dao.order.OrderDetailsDao;
import cn.gson.CRM.model.dao.product.ProductDao;
import cn.gson.CRM.model.dao.return_.ReturnDao;
import cn.gson.CRM.model.dao.return_.ReturnDetailDao;
import cn.gson.CRM.model.entity.Product;
import cn.gson.CRM.model.entity.ReceivePlan;
import cn.gson.CRM.model.entity.Return;
import cn.gson.CRM.model.entity.ReturnDetail;
import cn.gson.CRM.model.vo.OrderDetailVo;
import cn.gson.CRM.model.entity.Address;
import cn.gson.CRM.model.entity.Customer;
import cn.gson.CRM.model.entity.NewMessage;
import cn.gson.CRM.model.entity.Order;
import cn.gson.CRM.model.entity.Order.State;
import cn.gson.CRM.model.entity.OrderDetail;
import cn.gson.CRM.model.entity.PayPlan;
import cn.gson.CRM.model.entity.PayPlan.Type;
import cn.gson.CRM.service.OrderService;
import cn.gson.CRM.utils.ShareCodeUtil;

/**
* @author 邓安民:
* @version 创建时间：2018年4月8日 下午1:20:29
*订单控制类
*/
@Controller
@RequestMapping("order/order")
public class OrderManageController {
	@Autowired
	private ProductDao productDao;
	@Autowired
	private OrderService oService;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private ReceivePlanDao receivePlanDao;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private OrderDetailsDao orderDetailsDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private AddressDao addressDao;
	@Autowired
	private PayPlanDao payPlanDao;
	@Autowired 
	private ReturnDao returnDao;
	@Autowired
	private ReturnDetailDao returnDetailDao;
	@Autowired
	private ReceiveRecordDao receiveRecordDao;
	@RequestMapping
	public void index(){	
	}
	/**
	 * 分页条件查询订单
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param state
	 * @param theme
	 * @return
	 */
	@GetMapping("lists")
	@ResponseBody
	public Map<String,Object> orderListByPage(@RequestParam Integer page,//当前页
			@RequestParam(defaultValue="8")Integer rows,//页记录数
			@RequestParam(defaultValue="id")String sort,//排序属性
			@RequestParam(defaultValue="desc")String order,//排序类型
			String state,//订单状态
			String theme//主题
			){
			System.out.println(page+"当前页"+rows);
			System.out.println(sort+"排序"+order);
			Sort sort2;
			if(order.equals("desc")){
				 sort2=new Sort(Direction.DESC,sort);
			}else{
				 sort2=new Sort(Direction.ASC,sort);
			}
			Pageable pageable= new PageRequest(page-1, rows,sort2);
			if(!StringUtils.isEmpty(theme)||!StringUtils.isEmpty(state)){
				if(!StringUtils.isEmpty(theme)&&!StringUtils.isEmpty(state)){
					
					System.out.println("jjjjjjjjj:"+state+"=="+theme);
					return oService.finAllOrdersByWhere(State.valueOf(state),theme,pageable);//先把字符串类型转换成枚举类型
					
				}else if (!StringUtils.isEmpty(theme)&&StringUtils.isEmpty(state)){
					
					System.out.println("kkkkkkkkk:"+state+"=="+theme);
					return oService.finAllOrdersByTheme(theme,pageable);
					
				}else {
					System.out.println("lllllllll:"+state+"=="+theme);
					return oService.finAllOrdersByState(State.valueOf(state),pageable);//先把字符串类型转换成枚举类型
				}
			
			}else{

				return oService.finAllOrders(pageable);
			}

		
	}
	/**
	 * 已下单
	 * @return
	 */
	@GetMapping("xia")
	public String toOrderXia(){
		return "order/orderXia";
	}
	/**
	 * 已支付
	 * @return
	 */
	@GetMapping("pay")
	public String toOrderPay(){
		return "order/orderPay";
	}
	/**
	 * 已发货
	 * @return
	 */
	@GetMapping("send")
	public String toOrderSend(){
		return "order/orderSend";
	}
	/**
	 * 已完成
	 * @return
	 */
	@GetMapping("done")
	public String toOrderDone(){
		return "order/orderDone";
	}
	/**
	 * 已取消
	 * @return
	 */
	@GetMapping("cancel")
	public String toOrderCancel(){
		return "order/orderCancel";
	}
	/**
	 * 跳转到新增订单页面
	 * @return
	 */
	
	@GetMapping("/toAdd")
	public String toAdd(){	
		return "order/addOrder";		
	}
	/**
	 * 客户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("customerInfo/{id}")
	public String loadCustomer(@PathVariable Long id,Model model){
		System.out.println("-----------------------------------------------------"+id);
		model.addAttribute("c", customersDao.findCustomerInfo(id));
		return "order/customerInfo";
		
	}
	/**
	 * 订单详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/orderDetails/{id}")
	public String loadOrderDetails(@PathVariable Long id,Model model){
		model.addAttribute("o",orderDao.findOne(id) );
		model.addAttribute("od", orderDetailsDao.selectOrderAndDetails(id));
		System.out.println(orderDetailsDao.selectOrderAndDetails(id));
		return "order/orderDetails";
		
	}
	/**
	 * 添加新订单
	 */
	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject saveOrders(@Valid Order order,BindingResult br){
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("msg", "false");
		} else {
			//设置订单编号
			order.setOrderId(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
			Order order2=orderDao.save(order);//获取刚刚保存的对象
			
			NewMessage message = new NewMessage();
			message.setOrder(order);
			message.setType("新订单");
			messageDao.save(message);
			
			//产生一条回款记录，为总金额的百分之十
			ReceiveRecord receiveRecord=new ReceiveRecord(order2, order2.getTotal().doubleValue()* 0.1,
					cn.gson.CRM.model.entity.ReceiveRecord.Type.SUBMONEY, order2.getDate(), true);
			//System.out.println(receiveRecord+"===================");
			receiveRecordDao.save(receiveRecord);
			
			
			//产生一条回款计划
			 Date date=new Date();
			 
			 long time = date.getTime(); // 得到指定日期的毫秒数
			 long day = 7*24*60*60*1000; // 要加上的天数转换成毫秒数(一周)
			 time+=day; // 相加得到新的毫秒数
			Date lateTime =new Date(time); // 将毫秒数转换成日期
			
			ReceivePlan plan=new ReceivePlan( order2, order2.getTotal().doubleValue()*0.9, lateTime, order.getDate());
			receivePlanDao.save(plan);
			result.put("msg", order2.getId());
		}
		return result;
		
	}
	/**
	 * 编辑订单页面
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("toEdit/{id}")
	public String toEdit(@PathVariable Long id,Model model){
		Order order=orderDao.findOne(id);
		model.addAttribute("o", order);
		return "order/orderEdit";
		
	}
	/**
	 * 编辑订单
	 * @param order
	 * @param br
	 * @return
	 */
	@PostMapping("/orderEdit")
	@ResponseBody
	@Transactional
	public  JSONObject orderEdit(@Valid Order order,BindingResult br){
		JSONObject result=new JSONObject();
		if(br.hasErrors()){
			System.out.println(br);
			result.put("msg", "校验失败!系统异常");
			
		}else{
			orderDao.save(order);
			
		}
		return result;	
	}
	/**
	 * 添加订单详情
	 */
	@PostMapping("addDetails")
	@ResponseBody
	@Transactional
	public String saveDetails(String detail){
		try {
			JSONArray data=JSONArray.parseArray(detail);
			List<OrderDetail> oDetails=new ArrayList<>();
			for(int i=0;i<data.size();i++){
				JSONObject detail1=data.getJSONObject(i);
				OrderDetail orderDetail=new OrderDetail();
				orderDetail.setCount(detail1.getInteger("count"));
				orderDetail.setCost(detail1.getDouble("cost"));
				orderDetail.setSubtotal(detail1.getBigDecimal("subtotal"));
				orderDetail.setProduct(productDao.findOne(detail1.getLong("p_id")));
				orderDetail.setOrders(orderDao.findOne(detail1.getLong("order")));
				orderDetail.setState(1);
				oDetails.add(orderDetail);			
			}
			orderDetailsDao.save(oDetails);
			return "true";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "false";
		}	
	}

	/**
	 *订单详情编辑页面
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("toEditDetail/{id}")
	public String toEditDetail(@PathVariable Long id,Model model){
		model.addAttribute("order", id);
		return "order/orderDetailEdit";
	}
	/**
	 * 订单详情列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("detailList/{id}")
	public List<OrderDetailVo> detailList(@PathVariable Long id){
		List<OrderDetailVo> orderDetails=orderDetailsDao.selectOrderAndDetails(id);
		return orderDetails;
	}
	/**
	 * 订单详情编辑
	 */
	@RequestMapping({"detailEditFrom/{order}","detailEditFrom/{order}/{id}"})
	public String toDetailEditFrom(@PathVariable(required=false) Long id,
			@PathVariable(required=true)Long order,Model model){
		model.addAttribute("orderdam", orderDao.findOne(order));
		if(id!=null){
			model.addAttribute("od", orderDetailsDao.findOne(id));
			System.out.println(orderDetailsDao.findOne(id));
		}
		return "order/detailEditFrom";
	}
	/**
	 * 订单详情保存	
	 */
	@RequestMapping("detailEditFrom/save")
	@ResponseBody
	@Transactional
	public JSONObject saveDetailEditFrom(@Valid OrderDetail orderDetail,BindingResult br){
		JSONObject result=new JSONObject();
		if(br.hasErrors()){
			System.out.println(br);
			result.put("msg", "校验失败！系统异常");
		}else{		
			//保存订单详情
			OrderDetail orderDetail2 =orderDetailsDao.save(orderDetail);
			List<OrderDetail> oDetails=orderDetailsDao.ifSameProduct(orderDetail2.getOrders().getId(), orderDetail2.getProduct().getId());
			if(oDetails.size()==1){	//判断是否重复		
				//获取总金额
				BigDecimal total=orderDetailsDao.getTotalByOrder(orderDetail2.getOrders().getId());
				//重新设计订单的总金额
				Order order=orderDao.findOne(orderDetail2.getOrders().getId());
				order.setTotal(total);
				Order order2=orderDao.save(order);
				//修改定金的回款记录为订单金额的百分之十
				ReceiveRecord receiveRecord=receiveRecordDao.findByOrdersIdAndType(order2.getId(), cn.gson.CRM.model.entity.ReceiveRecord.Type.SUBMONEY);
				receiveRecord.setMoney(order2.getTotal().doubleValue()*0.1);
				receiveRecordDao.save(receiveRecord);
				//修改回款计划为订单金额的百分之九十
				ReceivePlan plan=receivePlanDao.findAllByOrdersId(order2.getId());
				plan.setMoney(order2.getTotal().doubleValue()*0.9);
				receivePlanDao.save(plan);
			}else{
				orderDetailsDao.delete(orderDetail2);
				result.put("msg", "操作失败！已存在此产品");
			}
		}
		return result;
		
	}
	/**
	 * 删除订单明细
	 * @param id
	 * @return
	 */
	@Transactional
	@ResponseBody
	@GetMapping("orderDetail/delete/{id}")
	public String  orderDetailDelete(@PathVariable Long id){
		OrderDetail orderDetail2=orderDetailsDao.findOne(id);
		orderDetailsDao.delete(id);
		//获取总金额
		BigDecimal total=orderDetailsDao.getTotalByOrder(orderDetail2.getOrders().getId());
		//重新设计订单的总金额
		Order order=orderDao.findOne(orderDetail2.getOrders().getId());
		order.setTotal(total);
		Order order2=orderDao.save(order);
		//修改回款计划
		ReceivePlan plan=receivePlanDao.findAllByOrdersId(order2.getId());
		if(plan!=null){
		plan.setMoney(order2.getTotal().doubleValue());
		receivePlanDao.save(plan);
		}	
		return "true";
	}
	/**
	 * 取消订单
	 * @param id
	 * @return
	 */
	@Transactional
	@ResponseBody
	@GetMapping("cancel/{id}")
	public String cancelOrder(@PathVariable Long id){
		
		Order order=orderDao.findOne(id);

		if(order.getState().equals(State.PAY)){//如果是已经付款则产生一条付款计划
			//产生一条付款计划
			 Date date=new Date();			 
			 long time = date.getTime(); // 得到指定日期的毫秒数
			 long day = 7*24*60*60*1000; // 要加上的天数转换成毫秒数(一周)
			 time+=day; // 相加得到新的毫秒数
			 Date lateTime =new Date(time); // 将毫秒数转换成日期
			 PayPlan payPlan=new PayPlan(order, order.getTotal()!=null?order.getTotal().doubleValue():0.00,
					 lateTime, new Date(),Type.CANCEL);
			 payPlanDao.save(payPlan);
			
		}else{			
			//删除汇款计划
			ReceivePlan plan=receivePlanDao.findAllByOrdersId(order.getId());	
			if(plan!=null){
			receivePlanDao.delete(plan);
			}
		}
		order.setState(State.CANCEL);
		orderDao.save(order);
	
		return "true";
				
	}
	/**
	 * 删除订单
	 * @param id
	 * @return
	 */
	@Transactional
	@ResponseBody
	@GetMapping("delete/{id}")
	public String deleteOrder(@PathVariable Long id){
		Order order=orderDao.findOne(id);
		List<OrderDetail> orderDetails=orderDetailsDao.findByOrdersId(order.getId());
		if(orderDetails.size()>0){
			//先删除订单详情
			orderDetailsDao.delete(orderDetails);
		}
		//再删除订单
		orderDao.delete(order);		
		return "true";
		
	}
	/**
	 * 编辑快递单号
	 */
	@GetMapping("shipmentForm/{id}")
	public String loadShipmentForm(@PathVariable Long id,Model model){
		model.addAttribute("o", orderDao.findOne(id));		
		return "order/shipmentForm";
		
	}
	/**
	 * 保存快递单号
	 * @param order
	 * @param br
	 * @return
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("shipment/save")
	public JSONObject editShipment(@Valid Order order,BindingResult br ){
		JSONObject result=new JSONObject();
		if(br.hasErrors()){
			result.put("msg", "校验失败！系统异常");
		}else{
			Order order2=orderDao.findOne(order.getId());
			order2.setExpressCompany(order.getExpressCompany());
			order2.setShipment(order.getShipment());
			orderDao.save(order2);
		}
		return result;
		
	}
	/**
	 * 加载退货表单
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("toOrderReturn/{id}")
	public String toOrderReturn(@PathVariable Long id,Model model){
		model.addAttribute("order",id);
		return "order/orderReturn";
		
	}
	/**
	 * 退货
	 * @param order
	 * @param br
	 * @return
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("return/{id}")
	public String editShipment(@PathVariable Long id ){
		OrderDetail orderDetail=orderDetailsDao.findOne(id);
		/**
		 * 产生退货记录
		 */
		Return return0;
		ReturnDetail returnDetail0;
		//先找到对应的退货单
		Return return1=returnDao.findByOrdersId(orderDetail.getOrders().getId());
		if(return1==null){//不存在
			//产生一个退货单号
			String  number=ShareCodeUtil.getCharAndNumr();		
			//产生退货单
			Return return2=new Return( orderDetail.getOrders(),number, new Date(),
					orderDetail.getSubtotal().doubleValue(),0.0, cn.gson.CRM.model.entity.Return.State.TUING);
			//产生退货单详情
			ReturnDetail returnDetail=new ReturnDetail( return2, orderDetail.getProduct(),
					orderDetail.getCost(), orderDetail.getCount(), orderDetail.getSubtotal());
			//保存退货单
			return0=returnDao.save(return2);
			//保存退单详情
			returnDetail0=returnDetailDao.save(returnDetail);
			
						
		}else{//已存在
			//产生退货单详情
			ReturnDetail returnDetail=new ReturnDetail( return1, orderDetail.getProduct(),
					orderDetail.getCost(), orderDetail.getCount(), orderDetail.getSubtotal());
			//保存退货详情
			returnDetail0=returnDetailDao.save(returnDetail);
			//统计退货单的金额
			BigDecimal total=returnDetailDao.getTotalByReturn(return1.getId());
			return1.setReturned(total.doubleValue());
			//保存退货单
			return0=returnDao.save(return1);			
		}
		//产生一条付款计划
		 Date date=new Date();			 
		 long time = date.getTime(); // 得到指定日期的毫秒数
		 long day = 7*24*60*60*1000; // 要加上的天数转换成毫秒数(一周)
		 time+=day; // 相加得到新的毫秒数
		 Date lateTime =new Date(time); // 将毫秒数转换成日期
		 PayPlan payPlan=new PayPlan(return0, returnDetail0.getSubtotal().doubleValue(), lateTime, new Date(), Type.RETURN);
		 payPlanDao.save(payPlan);
		//设置状态为退货
		orderDetail.setState(0);
		
		return "true";
		
	}
	
	/**
	 * 获取产品对象
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("/product")
	public Product loadProduct(Long id){
		Product product=productDao.findOne(id);
		return product;
		
				
	}
	/**
	 * 获取产品列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("/productList")
	public List<Product> loadProducts(){
		List<Product> products=(List<Product>) productDao.findAll();
		return products;			
	}
	/**
	 * 获取客户列表
	 * @return
	 */
	@ResponseBody
	@GetMapping("customerList")
	public Iterable<Customer> loadCustomers(){
		return customersDao.findAll();
		
	}
	/**
	 * 获取用户地址列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("addressList/{id}")
	public Iterable<Address> loadAddress(@PathVariable Long id){
		return addressDao.findByCustomer(id);
	}
	
	

	
	
	
	/**
	 * 获取物流(测试单号：3950051412724)
	 * @param identify
	 * @param shipment
	 * @param model
	 * @return
	 */
	@GetMapping("shipment/{identify}/{shipment}")
	public String getshipment(@PathVariable String identify,@PathVariable String shipment,Model model){
		String url="http://www.kuaidi100.com/query?id=1&type="+identify+"&postid="+shipment+"&valicode=&temp=0.20180725857720894";
		model.addAttribute("shipment", JSONObject.parseObject(loadJson(url)));
		return "order/shipment";
		
	}
	
	/**
	 * 读取远程json
	 * @param url
	 * @return
	 */
	public String loadJson (String url) {  
        StringBuilder json = new StringBuilder();                  
        try {  
            URL urlObject = new URL(url);  
            URLConnection uc = urlObject.openConnection();  
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));  
            String inputLine = null;  
            while ( (inputLine = in.readLine()) != null) {  
                json.append(inputLine);  
            }  
            in.close();  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return json.toString();  
    } 


}


 